package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

//    @RequiredPermission(name="员工列表",expression = "employee:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo")EmployeeQueryObject qo){
        model.addAttribute("pageResult", employeeService.query(qo));

        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);
        // /WEB-INF/views/employee/list.jsp
        return "employee/list";
    }

    // 处理删除请求
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            employeeService.delete(id);
        }
        return "redirect:/employee/list.do"; // 本质让浏览器再发送一次请求到 http://localhost/employee/list.do
    }

    // 处理去保存请求
    @RequestMapping("/input")
    public String input(Long id, Model model){
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);

        //查询所有角色
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles",roles);

        if (id != null) {
            model.addAttribute("employee",
                employeeService.get(id));
        }
        return "employee/input";
    }

    // 处理保存请求
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee,Long[] ids) {
        try {
            if (employee.getId() != null) { // 修改
                employeeService.update(employee,ids);
            }else { // 保存
                employeeService.save(employee,ids);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"保存失败");
        }
    }


    @RequestMapping("/batchDelete")
    @ResponseBody  /**@RequestParam("ids[]") */
    public JsonResult batchDelete(Long[] ids) {
        try {
            if (ids != null && ids.length > 0) { // 修改
                employeeService.batchDelete(ids);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"删除失败");
        }
    }

    @RequestMapping("/checkName")
    @ResponseBody
    public Map checkName(String name){
        HashMap<String, Boolean> map = new HashMap<>();
        Employee employee = employeeService.selectByName(name);
     /*   if(employee!=null){ //已被注册，验证失败
            map.put("valid",false);
        }else{ //未被注册，验证成功
            map.put("valid",true);
        }*/
        map.put("valid",employee==null);
        return map;
    }


    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //调用业务层的方法
        HSSFWorkbook workbook = employeeService.exportXls();
        //输出到浏览器
        workbook.write(response.getOutputStream());

      /*  List<Employee> employees = employeeService.listAll();
        EasyExcel.write(response.getOutputStream(), Employee.class).sheet("通讯录").doWrite(employees);
*/
    }

    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws IOException {
        //读取上次的文件的文件输入流，封装到workbook中
        HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
        employeeService.importXls(workbook);
        return new JsonResult();
    }

}
